﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace Yunzuan.Foundation.Serializer
{
    /// <summary>
    /// Json序列化工具
    /// </summary>
    public class Json
    {
        /// <summary>
        /// 序列化Json
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static string Serialize(object source)
        {
            return JsonConvert.SerializeObject(source, GetJsonSetting());
        }

        /// <summary>
        /// 反序列化Json
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="json"></param>
        /// <returns></returns>
        public static T Deserialize<T>(string json) where T : class, new()
        {
            return JsonConvert.DeserializeObject(json, typeof(T), GetDeserializeJsonSetting()) as T;
        }

        /// <summary>
        /// 反序列化Json
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="json"></param>
        /// <returns></returns>
        public static object Deserialize(string json, Type targetType)
        {
            return JsonConvert.DeserializeObject(json, targetType, GetDeserializeJsonSetting());
        }

        private static JsonSerializerSettings GetJsonSetting()
        {
            IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();
            timeConverter.DateTimeFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss";
            JsonSerializerSettings setting = new JsonSerializerSettings()
            {
                MissingMemberHandling = MissingMemberHandling.Ignore,
                NullValueHandling = NullValueHandling.Ignore,
            };
            setting.Converters.Add(timeConverter);

            return setting;
        }

        public static JsonSerializerSettings GetDeserializeJsonSetting()
        {
            JsonSerializerSettings setting = new JsonSerializerSettings()
            {
                MissingMemberHandling = MissingMemberHandling.Ignore,
                NullValueHandling = NullValueHandling.Ignore
            };
            setting.Error = new EventHandler<Newtonsoft.Json.Serialization.ErrorEventArgs>((o, e) =>
            {
                //记录日志

                e.ErrorContext.Handled = true;
            });
            return setting;
        }
    }
}
